package com.xinxing.city.recovery.tts;

import android.content.Context;
import android.media.AudioManager;
import android.speech.tts.TextToSpeech;

import com.xinxing.city.recovery.interfaces.ITtsService;

import java.util.HashMap;
import java.util.Locale;



/**
 * Created by icyhy on 2016/6/14.
 */
public class TtsService implements ITtsService {

    private TextToSpeech tts;
    private boolean initialized;
    AudioManager audioManager;
    /**
     * 启动tts语音服务
     */
    @Override
    public void start(Context context) {
        if (initialized)
            return;
        audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        tts = new TextToSpeech(context, this);
        initialized = true;
    }

    @Override
    public void stop() {
        if (tts != null) {
            tts.stop();
            tts.shutdown();
            tts = null;
            initialized = false;
        }
    }

    @Override
    public void playEarcon() {
        if (tts != null)
            tts.playEarcon("lingdong", TextToSpeech.QUEUE_ADD, null);
    }


    @Override
    public void speak(String text) {
        tts.speak(text, TextToSpeech.QUEUE_FLUSH,null);
    }

    /**
     * 中断当前播放
     */
    @Override
    public void interrupt() {
        if (tts != null)
            tts.stop();
    }

    @Override
    public void onUtteranceCompleted(String utteranceId) {
        android.util.Log.i("TTS", "  ====== "+utteranceId);
    }

    @Override
    public void onInit(int status) {
        if (status == TextToSpeech.SUCCESS) {
            android.util.Log.e("TTS","tts初始化成功");
            //指定当前朗读的是中文，如果不是给予提示
            int result = tts.setLanguage(Locale.CHINESE);//制定当前阅读的是中文
            if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
                //Toast.makeText((Activity)activity, "不支持中文TTS语音", Toast.LENGTH_SHORT).show();
                android.util.Log.e("TTS","不支持中文TTS语音");
            }
            tts.setOnUtteranceCompletedListener(new TextToSpeech.OnUtteranceCompletedListener() {
                @Override
                public void onUtteranceCompleted(String utteranceId) {
//                    List<String> params = Lists.newArrayList();
//                    EventBus.getDefault().post(new KernelAction(KernelActions.TTS_END, params));
                }
            });

        } else {
            android.util.Log.e("TTS","tts初始化失败");
        }
    }


}
